import React, { useState, useContext } from 'react';
import { Input, Button, Drawer, Form, Radio, Divider, Table, Select, message } from 'antd';
import { connect, useDispatch } from 'umi';
import { MOBILE_REG, EMAIL_REG } from '@/utils/const';
import OrgTreeSelect from '@/components/OrgTreeSelect';
import useEnum from '@/hooks/useEnum';
import styles from './StaffManageAddEdit.less';

const { Option } = Select;
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  const onRowValuesChange = (changedValues, allValues) => {
    if (changedValues.orgName) {
      form.setFieldsValue({ positionName: undefined });
    }
  };
  return (
    <Form form={form} component={false} onValuesChange={onRowValuesChange}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  drawerType,
  positionList,
  handleTreeChange,
  handleSelectChange,
  ...restProps
}) => {
  const [editing, setEditing] = useState(
    (editable && record && typeof record[dataIndex] === 'undefined')
  );
  const form = useContext(EditableContext);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const handleTreeSelectChange = (value, node) => {
    handleTreeChange(value, node, record);
  };

  const selectChangePostion = (value, node) => {
    handleSelectChange(value, node, record);
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
      >
        {
          dataIndex === 'orgName'
            ? <OrgTreeSelect placeholder="请选择" onSelect={handleTreeSelectChange} />
            : (
              <Select placeholder="请选择" onChange={selectChangePostion}>
                {positionList.length > 0 ? positionList.map(item => <Option key={item.id}>{item.name}</Option>) : null}
              </Select>
            )
        }
      </Form.Item>
    )
      : (
        <div
          className="editable-cell-value-wrap"
          style={{ paddingRight: 24 }}
          onClick={drawerType === 'look' ? () => { } : toggleEdit}
        >
          {children}
        </div>
      );
  }
  return <td {...restProps}>{childNode}</td>;
};

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const validateMessages = {
  // eslint-disable-next-line no-template-curly-in-string
  required: '${label}是必填项!',
};

const StaffManageAddEdit = (props) => {
  const { drawerType, editData, lookDisabled, handleCloseDrawer } = props;
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const [positionList, setPositionList] = useState([]);
  const [tableVisible] = useState(true);
  const [orgListData, setOrgListData] = useState(drawerType === 'add' ? [] : (editData.orgAndPositionList || []));
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const educationEnum = useEnum('100');
  const professionalTitleEnum = useEnum('200');
  const genderEnum = useEnum('300');
  const politicalFaceEnum = useEnum('400');

  const returnTitle = (type) => {
    if (type === 'add') {
      return '添加员工';
    } else if (type === 'edit') {
      return '编辑员工';
    }
    return '查看员工';
  };
  const handleSubmit = () => {
    const { validateFields } = form;

    validateFields().then((values) => {
      const list = [];
      const subList = [...orgListData];
      subList.forEach((item) => {
        if (item.employeeOrgId !== undefined && item.employeePositionId !== undefined) {
          list.push({ orgId: item.employeeOrgId, positionId: item.employeePositionId });
        }
      });
      const params = {
        orgAndEmployeeInfoList: list,
        ...values,
      };
      let subDrawerType = 'stuffManageModel/addStuff';
      if (drawerType !== 'add') {
        params.id = editData.id;
        subDrawerType = 'stuffManageModel/updateStuff';
      }
      dispatch({
        type: subDrawerType,
        payload: params,
      }).then((res) => {
        const { code, message: errMsg } = res;
        if (code === 0) {
          message.success(drawerType === 'add' ? '添加员工成功!' : '修改员工成功!');
          handleCloseDrawer(true);
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  // 新增组织信息数据
  const addTableRow = () => {
    const data = { id: `new${orgListData.length + 1}`, employeeOrgId: undefined, employeePositionId: undefined };
    if (drawerType === 'add') {
      setOrgListData([...orgListData, data]);
    } else if (drawerType === 'edit') {
      setOrgListData([...orgListData, data]);
    }
  };

  const deleteRow = (record) => {
    const newList = orgListData.filter(item => item !== record);
    setOrgListData(newList);
  };

  const handleTreeChange = (value, node, record) => {
    if (drawerType === 'add') {
      const newList = [...orgListData].map((item) => {
        if (item.id === record.id) {
          return { ...item, employeeOrgId: node.value, employeePositionId: undefined };
        }
        return item;
      });
      setOrgListData(newList);
    } else if (drawerType === 'edit') {
      const newEditList = [...orgListData].map((item) => {
        if (item.id === record.id) {
          return { ...item, employeeOrgId: node.value, employeePositionId: undefined };
        }
        return item;
      });
      setOrgListData(newEditList);
    }

    dispatch({
      type: 'stuffManageModel/searchPosition',
      payload: { orgId: node.value },
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0) {
        setPositionList(data);
      } else {
        message.error(errMsg);
      }
    });
  };

  const handleSelectChange = (value, node, record) => {
    if (drawerType === 'add') {
      const newList = [...orgListData].map(
        item => item.id === record.id ? { ...item, employeePositionId: Number(node.key) } : item
      );
      setOrgListData(newList);
    } else if (drawerType === 'edit') {
      const newEditList = [...orgListData].map(
        item => item.id === record.id ? { ...item, employeePositionId: Number(node.key) } : item
      );
      setOrgListData(newEditList);
    }
  };

  const columns = [
    {
      title: '*组织',
      key: 'orgName',
      dataIndex: 'orgName',
      editable: true,
    },
    {
      title: '*岗位',
      key: 'positionName',
      dataIndex: 'positionName',
      editable: true,
    },
    {
      title: '操作',
      key: '',
      render: (text, record) => lookDisabled ? null : <a onClick={() => deleteRow(record)}>删除</a>,
    },
  ];

  const columnsData = columns.map((col) => {
    if (!col.editable) { return col; }
    return {
      ...col,
      onCell: record => ({
        record,
        drawerType,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        positionList,
        handleTreeChange,
        handleSelectChange,
      }),
    };
  });

  return (
    <Drawer
      title={returnTitle(drawerType)}
      width={600}
      placement="right"
      onClose={handleCloseDrawer}
      visible
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleCloseDrawer} style={{ marginRight: 8 }}>
            取消
          </Button>
          {drawerType === 'look' ? null : (
            <Button onClick={handleSubmit} type="primary">
              {drawerType === 'add' ? '添加' : '保存'}
            </Button>
          )}
        </div>
      )}
    >
      <div className={styles.drawerWrapper}>
        <div className={styles.basicInfo}> 基本信息 </div>
        <Form {...layout} form={form} name="nest-messages" validateMessages={validateMessages}>
          <Form.Item
            label="工号"
            name="employeeCode"
            rules={[{ required: true }, { pattern: '^[0-9]*$', message: '工号为数字' }]}
            initialValue={editData.employeeCode}
          >
            <Input placeholder="请输入工号" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="employeeName"
            rules={[{ required: true }]}
            initialValue={editData.employeeName}
          >
            <Input placeholder="请输入姓名" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="员工性质"
            name="employeeType"
            rules={[{ required: true }]}
            initialValue={editData.employeeType}
          >
            <Radio.Group disabled={lookDisabled}>
              <Radio value={2}>内部</Radio>
              <Radio value={1}>外包</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="性别"
            name="gender"
            rules={[{ required: true }]}
            initialValue={editData.gender}
          >
            <Select placeholder="请选择性别" disabled={lookDisabled}>
              {genderEnum.map(item => <Option key={item.code}>{item.name}</Option>)}
            </Select>
          </Form.Item>

          <Form.Item
            label="政治面貌"
            name="politicalFace"
            initialValue={editData.politicalFace}
          >
            <Select placeholder="请选择政治面貌" disabled={lookDisabled}>
              {politicalFaceEnum.map(item => <Option key={item.code}>{item.name}</Option>)}
            </Select>
          </Form.Item>

          <Form.Item
            label="学历"
            name="degree"
            initialValue={editData.degree}
          >
            <Select placeholder="请选择学历" disabled={lookDisabled}>
              {educationEnum.map(item => <Option key={item.code}>{item.name}</Option>)}
            </Select>
          </Form.Item>

          <Form.Item
            label="职称"
            name="professionalTitle"
            initialValue={editData.professionalTitle}
          >
            <Select placeholder="请选择职称" disabled={lookDisabled}>
              {professionalTitleEnum.map(item => <Option key={item.code}>{item.name}</Option>)}
            </Select>
          </Form.Item>

          <Form.Item
            label="英文名"
            name="employeeEnglishName"
            initialValue={editData.employeeEnglishName}
            rules={[
              { pattern: /^[A-Za-z]*(\s[A-Za-z]*)*$/g, message: '请不要输入英文字符和空格以外的字符' },
              { max: 255, message: '英文名不能超过 255 个字符' },
            ]}
          >
            <Input placeholder="请输英文名" disabled={lookDisabled} />
          </Form.Item>

          <Form.Item
            label="排序编号"
            name="employeeOrderNo"
            initialValue={editData.employeeOrderNo}
            rules={[{ pattern: /^[1-9][0-9]{0,3}$/g, message: '请输入 1 ~ 9999 范围内的正整数' }]}
          >
            <Input placeholder="请输排序编号" disabled={lookDisabled} />
          </Form.Item>

          <Form.Item
            label="联系电话"
            name="mobilePhone"
            rules={[{ pattern: MOBILE_REG, message: '手机号不正确，请输入正确的手机号码！' }, { required: true }]}
            initialValue={editData.mobilePhone}
          >
            <Input placeholder="请输入手机号码" maxLength={11} disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[{ pattern: EMAIL_REG, message: '请填写正确的邮箱！' }]}
            initialValue={editData.email}
          >
            <Input placeholder="请输入邮箱" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="办公地点"
            name="officeAddress"
            initialValue={editData.officeAddress}
          >
            <Input placeholder="请输入办公地点" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="办公室电话"
            name="officePhone"
            initialValue={editData.officePhone}
          >
            <Input placeholder="请输入办公电话" disabled={lookDisabled} />
          </Form.Item>
        </Form>
        <Divider />
        <div className={styles.orgInfo}>
          <span className={styles.orgTitle}>组织信息</span>
          {lookDisabled ? <span /> : <span className={styles.toggleFont} onClick={addTableRow}>新增</span>}
        </div>
        <div style={{ display: tableVisible ? 'block' : 'none' }}>
          <Table
            rowKey="id"
            components={components}
            columns={columnsData}
            dataSource={orgListData}
            pagination={false}
          />
        </div>
      </div>
    </Drawer>
  );
};

export default connect(state => state)(StaffManageAddEdit);
